<?php

use Hashids\Hashids;
use models\Business\Album;
use models\Business\Booking;
use models\Business\Coupon;
use models\Business\Order;
use models\Business\RefundInfo;
use models\Exception\Business\AlibabaproductException;
use models\Exception\Business\BookingException;
use models\Exception\Business\OrderException;
use models\Service\SystemService;
use youliPhpLib\Common\PwdAss;
use youliPhpLib\Common\RequestHelper;
use youliPhpLib\Common\RsaOperation;
use youliPhpLib\Common\StringOperation;
use Yaf\Registry;
use models\Exception\DAO\ModelSqlException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use Task\client;
use models\Business\Alibaba;
use models\Business\Tbk\Taobao\TbkSdk;

/**
 * Class CommonController
 * @SWG\Swagger(
 *   schemes={"http"},
 *   host="www.ylmall.com",
 *   basePath="/",
 *   info={
 *     "title"="论坛",
 *     "version"="1.0.0",
 *     "description" = "接口测试接口与文档",
 *     "contact":
 *     {
 *          "email":"huangxu4328@gmail.com"
 *     },
 *   },
 *     @SWG\Definition(
 *          type="object",
 *          definition="links",
 *          required={"next_page", "prev_page"},
 *          @SWG\Property(property="next_page", type="integer", format="int32", description="下一页页码"),
 *          @SWG\Property(property="prev_page", type="integer", format="int32", description="上一页页码")
 *     ),
 *     @SWG\Definition(
 *          type="object",
 *          definition="meta",
 *          required={"total", "per_page", "total_pages", "current_page", "count"},
 *          @SWG\Property(property="total", type="integer", format="int32", description="总条目"),
 *          @SWG\Property(property="per_page", type="integer", format="int32", description="每页显示条目"),
 *          @SWG\Property(property="total_pages", type="integer", format="int32", description="总页数"),
 *          @SWG\Property(property="current_page", type="integer", format="int32", description="当前页"),
 *          @SWG\Property(property="count", type="integer", format="int32", description="当前也总条目"),
 *          @SWG\Property(property="links", type="object", ref="#/definitions/links", description="上一页下一页对象")
 *     ),
 *     @SWG\Definition(
 *          type="object",
 *          definition="unauthorized",
 *          required={"errno", "errmsg", "result"},
 *          @SWG\Property(property="errno", type="integer", format="int32", description="错误编号"),
 *          @SWG\Property(property="errmsg", type="string", format="string", description="错误信息提示"),
 *          @SWG\Property(property="result", type="object", description="空对象")
 *     )
 * )
 */
class IndexController extends ApiBaseController
{

    public function tbkAction() {

        $sn = '202008042007480643377924';
        $action = 'failure';
        $res = \models\Business\JPush::withdrawPush($sn, $action);
        var_dump($res);
        exit();

        $order = \models\Business\Tbk\TbkOrder::getOrderList([
            'order_stats' => 2
        ]);
        if (! $order || $order['meta']['total'] <= 0)
            throw new \models\Exception\Business\TbkorderException(\models\Exception\Business\TbkorderException::TBKORDER_IS_NOT_EXISTS,
                \models\Exception\Business\TbkorderException::TBKORDER_IS_NOT_EXISTS_NO);

        $client = new client();
        $client->connect();
        foreach ($order['data'] as $order_info) {
            var_dump($order_info['order_sn']);

            try {
                $client->chkTbkOrderIsSettled($order_info['order_sn'],
                    $order_info['pay_time'], date('Y-m-d H:i:s', strtotime($order_info['pay_time']) + 60));
            } catch (Exception $e) {
                Registry::get('crontab_log')->err("调用chkTbkOrderIsSettled失败" . $e->getMessage());
            }
        }
        $client->close();
        exit();

//        $tbk = \models\Service\TbkorderService::getInstance()->create('595297860931342899', 11);
//        exit();

//        $access_token = '62013078ac49a9cega99a4e06214d641da07c36c2a215d22208129349928';
//        $r = TbkSdk::refreshToken($access_token);
//        var_dump($r);
        exit();
        /*$str = '{"gmt_create":"2020-06-04 06:29:00","charset":"UTF-8","seller_email":"youlikaifa@163.com","subject":"\u5378\u5986\u6c3468ml \u65c5\u884c\u88c5\u65e0\u523a\u6fc0\u8138\u90e8\u5507\u90e8 \u6e05\u6d01\u723d\u80a4\u6c34\u62a4\u80a4\u54c1\u8d60\u54c1\u4e00\u4ef6\u4ee3\u53d1","sign":"VnNaoo5ofaEWzIaDHi9AWWu2sXmDcdqQ1q8F42U1Akq\/IESDailRs3HqMNFeLzxFhEB1HQV0xWf1Ag\/xZKRmNEgLG9NuX+LlZyz9bXFZkG1s3ATCMB+3+YRBvxzPMpJfoRhETaKAuWjBAfebWrn22C0J06WnY4W7FDhwMhWV9w9kFvo8kzi2d3c9khcbyfKsaNCOqcy5GCfb5\/yJFmRscpDmMuiK8CVs0\/QgKu98Pl7D0gdHHefgiT7xhhS1+H3lIguv27IVOSnP2dlBD4dze7VNJU0+NFY\/urbb1Pj0AYtMuh+7mBl8sTbfHoypR0Tzl11rQa0ahLgFbDcueKFo3A==","buyer_id":"2088302122327334","invoice_amount":"3.25","notify_id":"2020060400222062901027331457545648","fund_bill_list":"[{\"amount\":\"3.25\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"3.25","buyer_pay_amount":"3.25","app_id":"2021001159637030","sign_type":"RSA2","seller_id":"2088731721969746","gmt_payment":"2020-06-04 06:29:01","notify_time":"2020-06-04 06:29:02","version":"1.0","out_trade_no":"202006040627531698238224","total_amount":"3.25","trade_no":"2020060422001427331404287864","auth_app_id":"2021001159637030","buyer_logon_id":"hua***@163.com","point_amount":"0.00"}';
        $arr = json_decode($str, true);
        echo json_encode(['str' => http_build_query($arr)]);
        exit();

        $uuid = 'qqrwzqenp93nxyn0qm0xq3b4rb23ex55y9mjyj1j2p995533xj';//长连接
        var_dump($uuid);

        $invite_code_list = \models\Business\Member::genInviteCode($uuid);

        $result = false;
        while($result === false && count($invite_code_list) > 0) {
            $invite_code = array_shift($invite_code_list);
            var_dump($invite_code);
            var_dump(count($invite_code_list));
            var_dump($invite_code_list);
        }
        exit('done');*/

        /*$rsa = RsaOperation::getInstance(APP_PATH . '/public/test/alipay_private_key.pem', APP_PATH . '/public/test/youli_public_key.pem');
        $encrypt = $rsa->privateEncrypt('123');
        var_dump($encrypt);
        var_dump($rsa->publicDecrypt($encrypt));
        exit();*/
        /*$url = 'https://uland.taobao.com/coupon/edetail?ut_sk=1.WQW0GUW0LT0DAPErtcZGMXvi_21380790_1590492998393.Copy.windvane&relationId=2354763844&union_lens=lensId%3ATAPI%401590492996%400b0b26b2_0d6a_17250c5256f_392f%4001&sourceType=other&_afc_link=1&ybhpss=aWRlbnRpdHk9dHJhZGUmdHRpZD0yMDE0XzBfMjUyNDEzMjglNDBiYWljaHVhbl9pcGhvbmVfNC4wLjAuMg%3D%3D&activityId=9f5889425d00429fb7863f1ed0a7c034&u_channel=1-25241328&source=bc&suid=DF94D2E5-56D5-4ADD-8E10-26EE27436D43&scheme=tbopen&umpChannel=1-25241328&e=AB46XYz%252FVC4E%252BdAb1JoOOlAHDD%252BNwdkWMNiHGhM4pe28760JSi%252Fny9WuVUKDAymblJ%252FkaXrHHeBwhfcl2wS2jq%252Fsuwgi637OIJ1GtccYOa5CRwUqOc6y6%252FsnwWZGSCD41ug731VBEQm0m3Ckm6GN2CwynAdGnOngMmnVmWO1H8sxx1z66XWq%252BVLajOROSSHlgMTUWdWy6V3abo6aVDhuUA%253D%253D&traceId=0b012c2815904929969646989e&afcflow=com.guodongbaohe.app&xId=1ru1CCwEdfd6thVwTA86b16BUHJpr8qWZ9P7ekn2xwTo9h7Rz2ANp4w7ExHCnorUBFDWJxUu4Mwpwy26cbfqOjPQtUyM4SOVmMaX6HzwFchD&ttid=2014_0_25241328%40baichuan_iphone_4.0.0.2&sdkVersion=4.0.0.2&hasLoginToken=true&un=ecae42ec0b929f704b68d5f77a161062&share_crt_v=1&spm=a2159r.13376460.0.0&sp_tk=77+lM1JhbjFyMU83OVfvv6U=&cpp=1&shareurl=true&short_name=h.VlQcZPj&sm=583456&app=chrome';
        $url_arr = parse_url($url);
        parse_str($url_arr['query'], $array);
        var_dump($array);
        exit();*/

        // 厦门宥理79712这个账号的session，也就是淘宝授权登录接口返回的access_token的值
        $session = '620221598707a542cd63357ZZ2cd6986c8d4e33e72d688c2208129349928';
        $config = [
            'appkey' => '30144205',
            'secretKey' => '8f334c4c9ec2a23a24abb35391d69bc8',
//            'session' => $session,//授权接口（sc类的接口）需要带上
            'sandbox' => false,
        ];


        $client = new \TaobaoUnionSdk\TbkFatory($config);

//        $result = $client->tools->refreshToken(['refresh_token' => $session]);

        // 通过session与订单编号，查询淘宝的用户编号
        /*$sn = '594223366988342899';
        $result = $client->tools->getOpenUidByTrade([
            'tid' => $sn
        ]);*/

        /*$tpwd = 'fu植这行话€VFMd1IUyxIs€打楷👉淘宝👈或点几鏈→接https://m.tb.cn/h.VOiljct?sm=299501 至瀏lan嘂..【每日坚果大礼包8种混合坚果组合干果零食30包雪花酥材料网红礼盒】';
        $result = $client->item->extractClick('https://detail.tmall.com/item.htm?id=590889707992&ut_sk=1.WQW0GUW0LT0DAPErtcZGMXvi_21380790_1590819494619.Copy.1&sourceType=item&price=67.99-105.9&origin_price=78-178&suid=7523DD07-60D3-4482-B746-3C25F0EB0B09&shareUniqueId=487481840&un=ecae42ec0b929f704b68d5f77a161062&share_crt_v=1&spm=a2159r.13376460.0.0&sp_tk=4oKsVkZNZDFJVXl4SXPigqw=&cpp=1&shareurl=true&short_name=h.VOiljct&sm=299501&app=chrome');
        if ($result == false) {
            var_dump($client->getError());
        }
        var_dump($result);*/

        /*$result = $client->order->get([
            'start_time' => '2020-05-26 20:00:00',
            'end_time' => '2020-05-26 22:00:00',
        ]);*/

        /*$item_id = '528267806516';
        $activity_id = '32e83bd96c454f9ebb4ba6c66aec426f';

        $result = $client->coupon->get([
            'activity_id' => $activity_id,
            'item_id' => $item_id
        ]);*/

        /*$coupon_url = 'https://uland.taobao.com/quan/detail?sellerId=2772257399&activityId=32e83bd96c454f9ebb4ba6c66aec426f&pid=mm_17870615_7714381_156512340';
        $result = $client->tools->createTpwd([
            'text' => '【小树苗】儿童牙膏无氟可吞咽牙膏',
            'url' => $coupon_url,
            'logo' => 'http://imgproxy.18cap.cn/imgextra/i3/1060894880/*o1*c*n01n8*p*b*g41lv5*jdeej6r_!!1060894880.jpg_400x400.jpg'
        ]);*/


        if ($result == false) {
            var_dump($client->getError());
        }

        var_dump($result);exit();
        echo json_encode($result);
    }

    public function refundReturnAction()
    {
        // 退款、退货
        // 1688订单编号 order表中的trade_order_sn
        $alibaba_order_id = '1688-orderId-' . time();
        // 退款的订单状态
        //$stats = 1;
        // 退货的订单状态
        $stats = 2;

        $refund_reasons_list = Alibaba::getTradeRefundReasonList($alibaba_order_id, $stats);

        // 订单金额 单位分
        $amount = 720;
        // 运费 单位分
        $carriage = 100;
        // 退款原因编号, 客户端、前端提交
        // 测试条件下为随机数
        $key       = array_rand($refund_reasons_list, 1);
        $reason_id = $refund_reasons_list[$key]['id'];
        // 退货、退款原因客户端、前端提交
        $description = "退货、退款原因";
        // 退货凭证 客户度、前端提交
        $vouchers = ['http://www.ylmall.com/upload/sku/5e8170c255760.jpg', 'http://www.ylmall.com/upload/sku/5e816796b0b91.png'];

        // 上传凭证
        $vouchers_arr = Alibaba::tradeUploadRefundVoucher($vouchers);

        $res = Alibaba::getTradeCreateRefund($alibaba_order_id, $amount, $carriage, $reason_id, $description, $stats, $vouchers_arr);
        // 退款、退货订单号，需要保存到数据库中
        $refund_order_id = $res['result']['refundId'];

        // 退货的情况
        if ($stats === 2) {
            // 以下两个接口具体用哪个暂时也不清楚，等申请接口的时候再找小二问清楚
            // 获取所有的物流公司名称
            //$logistic_company_list = Alibaba::getLogisticsOpQueryLogisticCompanyList();
            // 查询自己联系物流的物流公司列表
            $logistic_company_list = Alibaba::getLogisticsOpQueryLogisticCompanyListOffline();

            // 物流公司编码, 客户端、前端提交
            // 测试条件下为随机数
            $key                  = array_rand($logistic_company_list, 1);
            $logistics_company_no = $logistic_company_list[$key]['id'];
            // 运单号，客户端、前端提交
            $freight_bill = '123312';
            // 发货说明，内容在2-200个字之间，客户端、前端提交
            $description = '123321';
            // 凭证图片URLs，uploadRefundVoucher接口返回结果
            $vouchers = ['http://www.ylmall.com/upload/product_main_image/5e817f251cdb7.jpg', 'http://www.ylmall.com/upload/product_main_image/5e8208f86ca55.png'];

            // 上传凭证
            $vouchers_arr = Alibaba::tradeUploadRefundVoucher($vouchers);

            $res = Alibaba::tradeRefundReturnGoods($refund_order_id, $logistics_company_no, $freight_bill, $description, $vouchers_arr);
            var_dump($res);
        }

    }

    public function order2alibabaAction()
    {
        // 用户收货地址编号，booking表中的address_id字段
        $address_id = 4;
        // 商品编号，booking表中的product_id字段
        $product_id = '584051070147';
        // 商品sku的spec_id，alibabasku中的spec_id字段
        $spec_id = 'af478130f6c683c4c77bb511796617b8';
        // 下单商品数量，booking表中的num字段
        $num = 2;

        // 获取收货地址信息
        $address_list = Alibaba::getTradeAddressCodeParse($address_id);

        // 溢价模式预览订单
        Alibaba::getCreateOrderPreview4CybMedia($product_id, $num, $address_list, $spec_id);

        $order_info = [
            'sn'         => 'order的sn',
            'phone'      => '下单用户手机号',
            'product_id' => $product_id,
            'spec_id'    => $spec_id,
            'amount'     => 7.2,
            'num'        => '2'
        ];
        // 溢价模式创建订单
        $alibaba_order_id = Alibaba::getTradeCreateCybMedia($product_id, $num, $spec_id, $address_list, $order_info);

        Alibaba::tradePayProtocolPay($alibaba_order_id);

        exit('done');
    }

    public function indexAction()
    {
        $str = 'jsapi_ticket=kgt8ON7yVITDhtdwci0qeTAg8NzdOakQmdIE7IK3UmWzQ3j7Vf8QT2Sy5MQGws1RSBrm8hf3AeIL0zfdoUoiWA&nonceStr=xfsvmcxrpzbnuzxe&timestamp=1595945425&url=https://www.baidu.com';
        var_dump(sha1($str));
        $str = 'jsapi_ticket=kgt8ON7yVITDhtdwci0qeTAg8NzdOakQmdIE7IK3UmWzQ3j7Vf8QT2Sy5MQGws1RSBrm8hf3AeIL0zfdoUoiWA&nonceStr=xfsvmcxrpzbnuzxe&timestamp=1595945425&url=https://www.baidu.com';
        var_dump(sha1($str));
        exit();
        $signature = '';
        $original_string = 'jsapi_ticket=kgt8ON7yVITDhtdwci0qeTAg8NzdOakQmdIE7IK3UmX04niK5RPW3QYeufWwdeNP_jh2K51WZdGHBiyYxsTAFQ&noncestr=ditvtwwkkjaljiup&timestamp=1595820923&url=http://admin.douziyoupin.com/';
        parse_str($original_string, $original_arr);
        $original_arr['signature'] = $signature;
        var_dump($original_arr);
        exit();

        $url = '';
        $url = 'http://admin.douziyoupin.com/#/login';
//        $url = 'http://douziyoupin.com/product?type=tuan&id=603506980106';
        $oauth = \models\Business\TencentOauth::genWeChatJsApiSignature($url);
        var_dump($oauth);
        exit();

        $str = 'd8F9S6h0gYeUwmbXCTkpIJmk%2BywRrA2C7ODLVUSDAaNm%2FX0qq8xCqDxrk2RBMt2gncRgh0Mu9P28BQT1KGb455pgm37lH%2Fh9KHazNH40IKlUn2CLOhLcWkgXO5v9T6%2B28b25useWygZrllWGSwPnIUyY8P848EZ%2FZVKL8lmGOgSPq5m%2BTwH2xJYArk0GlUFUZIpGbk9%2B68nMo%2BhFo%2FaSylTU0%2Fhj1q0%2FdvOoM2B2goXUWrqm2eJrit%2F8NOzZLpAUsFOs1x5HNzdMMyChanAED2sNbFRM2xBai9jotC2SJFei%2Fp3NbQYJFZ7ve4n5ZQgTIUB%2F9QqLDs4n5uatrjSsNYIwffHN7%2FmwJTnEeiA5Tt%2F%2F88PMMRZ00j2rHj4i8yL10PeEkWQ8fJD6MS4bjbjwqKRZYSVTuoSQzMInKCJi6yeJIF4FtMkLCIhijYjkHMV3sgTqKSDYyeO2DoXcfZBfMslYchXa9L%2FTs4AIIASmmjthgq7b1dkoiJ4VAGMZmxKt2OhjxbemBzsdGmKmd4C3MIDg%2FP5uMZiBBYGQ5qfm8MaLCmfhlWLcgrPDSj%2Bb8KJdd8mATgEc5L6%2B0qovnouz%2FEQt0EyZvYJbxyuqb7qFRmFBcjFiDZWTz71Ih5LR5hMQU0WVeLDHi8vmzaD5Bh46vQHWzjOBl6D8V5IEGBEZhY4%3D';
        $str = urldecode($str);
        $rsa = RsaOperation::getInstance(Registry::get('config')['rsa']['public_pem'],
            Registry::get('config')['rsa']['private_pem']);
        var_dump($rsa->privateDecrypt($str));
        exit();

        /*$address_list = Alibaba::getTradeAddressCodeParse(4);
        var_dump($address_list);

        $cargoParamList = [
            [
                'specId' => '5c04744d98fb17bd357b450b699eb55f',
                'quantity' => 3,
                'offerId' => '588143593640'
            ]
        ];
        // 溢价模式预览订单
        $res = Alibaba::getCreateOrderPreview4CybMedia($address_list, $cargoParamList);
        var_dump($res['orderPreviewResuslt']);
        $order_info = [
            'mediaOrderId' => 'test' . time(),
            'phone'        => '13779957421',
            'offers'       => [
                'id'    => '588143593640',
                'num'   => 3,
                'price' => 37.57,
                'specId' => '5c04744d98fb17bd357b450b699eb55f'
            ],
        ];
        $result = Alibaba::getTradeCreateCybMedia($address_list, $cargoParamList, $order_info);
        var_dump($result);
        exit();*/
//        $user_group = Alibaba::getProductListCybUserGroup(1);
//        var_dump($user_group['result']['result']);
//        exit();
//        $product_list = Alibaba::getProductListCybUserGroupFeed(
//            6562, 1, 20, '', '');
//        var_dump($product_list);
//        exit();
        /*list($product_arr, $sku_arr, $product_sku_arr, $shipping_arr, $freight_arr) =
            Alibaba::getProductCpsMediaProductInfo('588544738068');
//
//        var_dump(Alibaba::getProductQueryOfferDetailActivity('588143593640'));
        var_dump($product_arr);
        var_dump($product_sku_arr);*/
        exit('done');
        $product_id = '584051070147';
        $member_id  = 3;
        $num        = 1;
        $redis      = Registry::get('redis');

        try {
            $redis->ping();
        } catch (\Exception $e) {
            $redis->auth(Registry::get('config')['redis']['master']['auth']);
        }

        $redis->select(Registry::get('config')['redis']['string']['db']);
        $key = "product:store:" . $product_id;
        // 库存不存在 或数量小于0
        if (!$redis->exists($key) || $redis->get($key) <= 0)
            throw new \Yaf\Exception("商品卖完了", 400);

        $buyer_arr     = $redis->zRange('product:buyer_list:' . $product_id, 0, -1, true);
        $member_id_arr = array_values($buyer_arr);
        if (count($member_id_arr) == $redis->get($key))
            throw new \Yaf\Exception("商品卖完了", 400);

        if (in_array($member_id, $member_id_arr) === true)
            throw new \Yaf\Exception("请等待上一次拼团结束再参与", 400);

        try {
            $redis->watch($key);
            $redis->decr($key);
            $redis->exec();

            $data = [
                // 付款信息订单号
                'trade_order_sn' => StringOperation::genOrderSn(),
                // 付款会员编号 Registry::get('jwt_info')->id获取
                'member_id'      => $member_id,
                // 商品编号
                'product_id'     => $product_id,
                // 商品数量
                'num'            => $num,
                // 商品sku编号 可能不存在
                'sku_id'         => '123',
                // 付款金额
                'amount'         => 9.9,
                // 时间
                'created_at'     => date('Y-m-d H:i:s', time()),
            ];
            $redis->zAdd('product:wait4pay:' . $product_id, [], $member_id, json_encode($data));
        } catch (Exception $e) {
            throw new \Yaf\Exception('抢购失败', 400);
        } finally {
            $redis->unwatch($key);
            $redis->close();
        }


//        $redis->select()
        exit();
//        $sql = "SELECT * FROM `announce` WHERE `title` like '%消息%' and (`stats` = 1 or `is_push` = 1)";
        $condition = [
            'groupOp' => 'and',
            'rules'   => [
                ['field' => 'title', 'op' => 'nc', 'data' => '%消息%'],
            ],
            'groups'  => [
                [
                    'groupOp' => 'or',
                    'rules'   => [
                        ['field' => 'stats', 'op' => 'eq', 'data' => 1],
                        ['field' => 'is_push', 'op' => 'eq', 'data' => 1],
                    ]
                ]
            ]
        ];
        $res       = \models\Service\AnnounceService::getInstance()->getList(1, 10, 'desc', 'id', $condition);
        var_dump($res);
        exit();
        $client = new client();
        try {
            $client->connect();
            // 1688商品采集
//            $client->listCybUserGroup(1);
            // 启用异步任务获取指定分类下的所有商品分类 直到叶子级分类
            // 改方法需要放到后台的商品分类管理里
            $client->categoryGet(Registry::get('parameters')['category_id']);
        } catch (Exception $e) {
            echo $e->getMessage();
        } finally {
            exit('done');
        }

        // 省市区县街道数据测试
//        $res = \models\Business\Location::getLocation();
        $res = \models\Business\Location::getLocation('', 1, 2);
        var_dump($res);
//        $res = \models\Business\Location::getLocation('350000000000', 2);
//        var_dump($res);
//        $res = \models\Business\Location::getLocation('350200000000', 3);
//        var_dump($res);
//        $res = \models\Business\Location::getLocation('350205000000', 4);
//        var_dump($res);
        exit();

        $res = \models\Business\PicCode::genPicCode('13779957421', 'register');
        var_dump($res);

        try {
//            $role_list = \models\Service\RoleService::getInstance()->getList(1, 20, 'desc', 'id', []);
            $role_list = \models\Service\RoleService::getInstance()->getList(1, 1, 'desc', 'id', [
                'groupOp' => 'AND', 'rules' => [
                    ['field' => 'id', 'op' => 'ge', 'data' => 1]
                ]
            ]);
            var_dump($role_list);
        } catch (ModelDriverException $e) {
        } catch (ModelException $e) {
        } catch (ModelReflectionException $e) {
        } catch (ModelSqlException $e) {
        } catch (ServiceException $e) {
        } catch (TransformerException $e) {
        }

        exit();

        $user_list = $this->login('13333333333', 'Aa123456');

//        $user_model = \models\DAO\UserModel::getInstance();
//        $sql = "SELECT u.`mobile`, u.`role`, r.`name` FROM `user` AS u LEFT JOIN `role` AS r ON u.`role` = r.`id` WHERE u.`mobile` = '13333333333'";
//        $user_list = $user_model->query($sql);

        try {
            /*$user_list = $this->getUserList(
                ['mobile' => '13333', 'stats' => 1]
            );
            var_dump($user_list);*/

            /*$user_list = \models\Service\UserService::getInstance()->getList(1, 2, 'desc', 'id',
                ['groupOp' => 'AND', 'rules' => [
                    ['field' => 'username', 'op' => 'in', 'data' => '13333333333, 13333333334']
                ]]);
            var_dump($user_list);
            exit();*/

            /*$mobile = '13333333339';
            $password = 'Aa123456';
            $hash_id = new Hashids('youli', 16, 'abcdefghijklmnopqrstuvwxyz01234569');
            $uuid = $hash_id->encode($mobile);
            $user_create_res = \models\Service\UserService::getInstance()->create($mobile, $password, '', 1, $mobile,
                0, $uuid, 0, 1, 1, true);
            var_dump($user_create_res);*/

            /*$user_update_res = \models\Service\UserService::getInstance()->update(['role' => 1, 'stats' => 1], $user_create_res['id'], true, $user_create_res['id']);
            var_dump($user_update_res);*/

            /*$user_delete_res = \models\Service\UserService::getInstance()->delete($user_create_res['id'], true, $user_create_res['id']);
            var_dump($user_delete_res);*/


            /*$user_list = $this->getUserList(
                ['mobile' => '13111', 'stats' => 0]
            );
            var_dump($user_list);*/

            /*$user_list = \models\Service\UserService::getInstance()->getOne(76, true, 76);
            var_dump($user_list);*/

            /*$hash_id = new Hashids('youli', 16, 'abcdefghijklmnopqrstuvwxyz01234569');
            $user_list = \models\Service\UserService::getInstance()->batchInsert(
                [
                    ['mobile' => '13111111111', 'username' => '13111111111', 'password' => 'Aa123456', 'uuid' => $hash_id->encode('13111111111')],
                    ['mobile' => '13111111112', 'username' => '13111111112', 'password' => 'Aa123456', 'uuid' => $hash_id->encode('13111111112')]
                ], true
            );
            var_dump($user_list);*/

            if ('*' === $pwd = PwdAss::getInstance(8, true)->HashPassword('123'))
                throw new Exception('密码生成失败', 400);

            /*$user_list = \models\Service\UserService::getInstance()->batchUpdate([
                ['id' => 167, 'mobile' => '13111111113', 'stats' => 1],
                ['id' => 168, 'mobile' => '13111111114', 'stats' => 0]
            ], true);*/

            /*$user_list = \models\Service\UserService::getInstance()->batchDelete([167, 168], true);
            var_dump($user_list);*/
            var_dump($user_list);

        } catch (ServiceException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        } catch (Exception $e) {
            throw $e;
        }
        exit();

//        return $this->_responseJson($user_list, 000);
//        $str = '{
//            "data": "C\/lE32P\/w7NBdcTyy1Y3LJ43\/cKs8SGurq71zigvBAXp5gvvFRJeFcEsY8puFLRT3VUmY+ke\/4Pw\/UUA4GrMShG1WTLZWiVCz7g8dK6PN2hX\/YJ7myRWiexlh5o8VquT",
//            "encrypt_str": "bRwn5vpROwvfRy+pqf3wGTjP5yUT6CWTScP\/1\/Cwc1kZbBE75xuvAlYHKm4BG0kWIGLdUxJvxXyNyZ0RVPcmhZmb3V3s5V2Y5PgZGZeMeguto8W0EOFBCdVURkVS8N+kjoPwxk2SC1RAl6BoiO9gf93FxpXWkmdSeWY6zJZQz3GMGSAYUXvR\/D3vnlb57PXHfYHJzqIDcIqICtaGQwPQF9r1np986PfmrjyNfSPNK3edsudfxHIv9OZdWQ5dQELYYMN\/QXyqfKm8W\/aMNX4RxcAjwweUCdngP7Pm8XzhOYOM8QQYGoy7AjCtoG3rV2ZVP9oWSgcg6Z9bsCdw2UCdMBgUO\/qblixZga4H2Ljb2CCV9xt\/p+Yex68bZHzZZDSvD9kUkAFvyqF+TkHjobiMJ1Yn+sSWmwvigXlchE2eFnntUwkDXOOjGKFU++b1RFkDZEEY1VbuECfb4V\/M2NbQJY07x9lAnHIjCiZ+wd18695MhOOp0ICh+IslxM1Trufp82wR3B+bVjnKb93SuVGex3PEEzhdg4S5wFaE9S7R5vJcLJhfv32CMcehRolZBBHykhilsr+7XSfRClOGdnLsK3eo213T9g3aDAnJigP5Vk56xax632RLgs9PxG6QT8PCFeIcHf2KqHOMegXDFjRD40cZxPIvC1sfpXzElKef\/lA=",
//            "sign": "YdOl81rN3EpUq9NnF\/HXs0tBB6IR8n3RTdhoKacPQ5ixgf0jmwdnhOfVdbSaqN0gDbEMM8uaGZKT5Bhb2Di0tbtQIcESOWaJhwmDVvTV\/Ticq5wwYsN+wbECxWGcDkufyxSKEZc13tEUx6rpxFDHiaKtGHD4ToEI8M7dLl+\/nJoDeTxXXQBWP+au5ArAmcAoWrdczIqVCao7MOp5YI+oq1IZrUKWuuiLDy26lvyE0tBBzLPgHt5cPJdE\/imx+QcDno63JWYBWn1kbnAy7+\/tEvRRct78k8h9N52Y1YwrGulkUKA3UoLggjWOg\/uANivdp5wBZpWoYX\/M+egDarDJ0YqjkIsfBSairUzfaL149ftICIW5UyhiZoI+JhTEj3FW\/Ca\/pnHin\/afP5qUvsxPu2T4rgHvWrJtSS\/OuJ7Riy24uGi+JIMMyUhtTut9+knxmwTvZn\/R6xfulCkZXuNXMjJdJWTrNi9Ozw0yC+v8mofO2wcsXxA6fU6+45eGFvO7Q8mEAz6JTLPIbfXO3jDOXIDQ5rAw3Sf+8IFzoANkG3A+vSD+Nw6Qv31tmq+F8PgAZCvu0042caZgVaEuhJ+QF10Y7e5chJqM\/S5VTfOlR+y2OzJypC+vZKD+qnnkdPxhms0E2fa25Uuwi6mEgyLQyYjjjJldwIpU4EpR1lM99mA="
//        }';
//        $data = json_decode($str, true);
//
//        $sign = $data['sign'];
//        $data = [
//            'data' => $data['data'],
//            'encrypt_str' => $data['encrypt_str']
//        ];
//        ksort($data);
//        var_dump($data);
//        var_dump($sign);
//
        $response = 'success';
        Registry::get('notify_log')->debug('模拟商户收到异步回调:' . json_encode(Registry::get('parameters')) . '; 商户返回{' . $response . '}');
        // 解密参数
        $rsa = RsaOperation::getInstance(Registry::get('config')['rsa']['public_pem'], Registry::get('config')['rsa']['private_pem']);

//        var_dump($rsa->publicDecrypt($data['encrypt_str']));

        $sign = Registry::get('parameters')['sign'];
        $data = [
            'encrypt_str' => Registry::get('parameters')['encrypt_str'],
            'data'        => Registry::get('parameters')['data']
        ];
        ksort($data);

        Registry::get('notify_log')->debug('data:' . json_encode($data) . '; sign{' . $sign . '}');

        list($key, $iv) = explode('-', $rsa->publicDecrypt($data['encrypt_str']));
//        var_dump(urldecode(http_build_query($data)));
//        var_dump($sign);
//        var_dump($rsa->verify($sign, urldecode(http_build_query($data))));
//        exit();

        if ($rsa->verify($sign, urldecode(http_build_query($data))) === false)
            throw new Exception('222', 400);

        list($key, $iv) = explode('-', $rsa->publicDecrypt($data['encrypt_str']));
        Registry::get('notify_log')->debug('模拟商户收到异步回调:' . $key . '-' . $iv);
        $data     = \Common\AesUtil::getInstance($key, $iv)->decrypt($data['data']);
        $response = 'error';
        Registry::get('notify_log')->debug('模拟商户收到异步回调:' . $data . ', 返回结果: {' . $response . '}');
        return $this->_responseString($response);

        // 密码
        $pwd_ass = PwdAss::getInstance(6, true);
        $pwd     = 'aa123456';
        $new_pwd = $pwd_ass->HashPassword($pwd);
//        var_dump($new_pwd);
        $res = $pwd_ass->CheckPassword($pwd, $new_pwd);
//        var_dump($res);
//        echo __METHOD__;

        $mobile = '12312312312';
        $r      = StringOperation::mobileIsValid($mobile);

    }

    /**
     * 对指定订单进行订单状态查询
     * @throws \Yaf\Exception
     */
    public function queryOrderStatsAction()
    {
        $parameters = Registry::get('parameters');
        Pdd::createNotify($parameters['id'], true);
    }

    public function testAction()
    {

        $str = 'bYHBAymtk0namSPdFcObQhp/VV2ME4Ycgbexlli+SSW5cwMu70n+J7SX6syIQfXf7fq/WeJPIwVnwj729zAx+2d56PPLIYEcLglUNXPrR38WrkF0dIYRF9PL5FvE2kvLCjVQoCrBJM/y9O1sdRLejvt2HnYSTHotG7W6le/nqGhI9Pyzb04vUEGqqL/9nPMygxtb+Km3rb2b1ivTBXKND/VduztCs2FaQgnlIRn2g5SKciqr5BkXr0G/pr2u+42HUv5QdgRMM4elAERdqpUAfOZZ5E6j3cwT9FIGXapp6P7+qZk9slxUtcR+VYADk6k82Hwu4jTKUAmQ02XQwdXDdzaTui0JCUHzAXSyLVnBR/odG7d/gbxzv5He6tOiBLDhYygWwL8xTNGohIx/HomSBHvvjxrl48CDyXddMM0rbV71N0B6XOtKVrqJ5Fw4QAm1Hjj+ZLjMsnhMQj9X7IZ9wpELr85dSKm1gyaadQF+kxmqdqV8lph60Va0r5MnwlPcEr51dOvtHUanb/vJ6bBUVdk5Si/iFd10YbFHjpODQwpOUsKLpzRu5xu548eKRReWVrXu4BXEmN7A+5EiggHdtZVfC+ieEqegjWtzz6JA/AnXEmVFi0svzzpFBwsy0s7zyyFnCkrV8tsXu9urC6CNlBvDtblr/IbAWZDiMgrOy8s=';
        $rsa = RsaOperation::getInstance(Registry::get('config')['rsa']['public_pem'],
            Registry::get('config')['rsa']['private_pem']);
        var_dump($rsa->privateDecrypt($str));
        exit();
        exit('done');

        $sign = "Nm8yiTaWISr08j5zEA7fS7as6uicFt0e0Y4PLxJu9zFQuIN1hvz43/mBDL8b4UFCqm7ixQSGQe2G7xusd3jiFcK/ddrwOi6fZ7x12/A9Aiz56Osf0Fx8fI5Uzag9URM4hV1a4hWdtxMTRDloUSH8m5Gqw2noOI9zP1yj2I6Mdc1mvuHEu+sxdgyeU3/CUk3kWAGegIt2m1nyrAK4myXrWbJhC1q1DKW50T+f23jWL+RKHK1zkpx9UWW/VI4kpVC2vmc/2aOThWqOX6mlK7PgG7l/w54qODiGiMdlV9/XFSlGYjoAmcnPXR8BOZqdlt6VkTKTs0GfUm1PnK2sod6hl/9MuVK3j8FqWnGXKjBvREXY+7cHg1c6XM3tMryajzz7JenVpwgP39KRJMg5rbOXMxkxB0gaWacJxBST4r4DmJMFXNMn51V9NPVMwDNoPZvoxdMtKMuqX2M6NwYt8Nv+Tqc5osVpskZ/P/jcK5QVm4JNJYa8qM8CID9Qwb3BZyLA27DgTeWszj4mNRETOdcJUd3chi4+l4X3BdyWFy1c3Uawz6m0k6M4Y7V03d+LmXAsxhPsHusPHWXC4a+OSDQwFTwSzYJfzqpX9SDSNW9P9v/hetdWGwzP6YdvCM7CXaNuiUqgnY5xR717gV0rHxeAyn7sMLoEuB+Zt3i8nxRkyEA=";
        $sign = "M83v03E0c27txaaY4VsRL3X1eRehf4qLYth6YjWP6JqFKs3em5IZzTzYOPcHoj6VIOLaz1nGUQrwyejdvFcTwOYNuKAyjwlsFQfxIQ2PYgb2T1VjwoDq+ZoGb58VdVsb0lwK83/hKO4W9JaK0NdPLrpiOsW9hz9kwjuHAFUNY70ybzTCsFOE/PDi03YVWZPgwz+8Ylx+C38FxSgTB1i7Zq6XtSSJuGo/yqWo2Wcd/mzByQSK3XQtl/V0OoK5ZF3B0Bz/3wE5DDHUbGzGTGcnB9zAwEdxco6gKXy1TxZvaftIBYDS783PJtZIb3h6Y3zsotYkf+TnNTnP5+XBuDe2SScPSvxGFW+9VnKpRGIIRX5qgVrg7kn7avM0mLlZbUvu3G7QE2yQGzCXIcMXr+h+Xwc73dYxaJpxWKjnTLOENvtJUO72WO5AxKLYzvyqdzx4VwFC3AkLsmbPFW0zV8evNxhPsYPacAFaudZWeQZcqDnRlkfW2n3HOxBfcigDW+EDbRPMAV5qd5pF4xcDaFuSIEsBO/MjkbtW4JB3tmeZIfB6Gb6UhEEbZHleyuZkW2M/76LtAZU3g4JaezzgYrrwxJLz3Sx/CAMTmBSifZYXX4OK+qsZb9Ql6YcaWmT8Q1yei2UFUrh1Q0gQ6KjAK/OezyfSMnLL5HR8lSH6peCO9Zs=";

        $data = [
            'data'        => "7s0lnMCnISsmiiIxK+ygbw==",
            'encrypt_str' => "fGDJg+LQKnYmKl4K0THulZAYU+OfMxmn1L/UKvSeQO91IuI1LtaXVpJ+JH/AEGk01pT77tvgx1UrA0oC6LyHZH2WGZNq5itereKg14Lzk5ZxpPNG4SBekY0tQYVUtZgXIsVJEPa31wRx2uUltB3sVzmzuxz9X164aotQkGC0wrjQfafnuXYc+1wKlQONUhVdHCOU9OQOqAgoX0cPtqKMZln9dkpWvJEIq5QE9CGdDhudH78GYH2T2qLLEi4kX96wyCQ0kJm28Pl9Df2JWJLsw1H0nqIprpAF72m0aHkk6HsVuxNxF1aIWSUpJTHxi0MZDvZHK1cJTqhY9ZGUt/NINpoDG/EtbT6ABj446rliFZKrNTe85L+fAjb78SrJ2bl49/EmM8s4p+6FxM2M5dJtGqQNeriExiyplLO9zObYcPh+iiNAO4oVMC/kZq6E7IhcOL4XpkYGYkPrvq3jg5H+/rczRypBPk6NVeAy514YTszbjo65feDuNNy11rhk0zz5chm/8O4uZqKh+DgV768NXHdFKvk5ASVNWl52Zrueiuhs6Pr76opHefd8gwBGsbbc4oPImk+ofF3XggNvIz/9/UxujbdSbRu6U9OvSeLO7CGzwlq588w+33YFglYumo6uY/7HKOpLBm94s/GIvA/Gl3+RkXpmuSZapvZSmwxqSp4="
        ];
        ksort($data);

        $rsa  = \youliPhpLib\Common\RsaOperation::getInstance(Registry::get('config')['rsa']['public_pem'], Registry::get('config')['rsa']['private_pem']);
        $sign = $rsa->sign($data);
        var_dump($sign);
        var_dump(urldecode(http_build_query($data)));
        var_dump($rsa->verify($sign, urldecode(http_build_query($data))));


        exit();
        $ga = new PHPGangsta_GoogleAuthenticator();
        /*$secret = $ga->createSecret();
        var_dump($secret);

        $qrCodeUrl = $ga->getQRCodeGoogleUrl('Blog', $secret, "pdd");
        echo $qrCodeUrl;
        exit();*/
        $secret = '5COL6MTRFWOYH3YF';
        var_dump($secret);

        $code = Registry::get('parameters')['code'];
        $res  = $ga->verifyCode($secret, $code, 1);
        var_dump($res);
        exit();

        $parameters = Registry::get('parameters');
        Registry::get('user_log')->info("ip:" . StringOperation::getIP());
        Registry::get('user_log')->info("parameters:" . json_encode($parameters));
//        echo json_encode($this->getRequest()->getServers());
//        exit();
        $referer = $this->getRequest()->getServer('HTTP_REFERER');
        $referer = parse_url($referer);
        parse_str($referer['query'], $referer_arr);

        $url = isset($referer_arr['url']) ? base64_decode($referer_arr['url']) : '';
        if (!empty($url))
            Registry::get('user_log')->info("server:" . $url);

        Registry::get('user_log')->info("cookie:" . json_encode($_COOKIE));


        return $this->_responseJson(new stdClass(), '000', 'success');
    }

    public function test1Action()
    {

        $parameters = Registry::get('parameters');
        //付款信息订单号 booking中sn
        $parameters['sn'] = $sn_s = '202004141851230643318735';//,202004141851230643318735';
        //$parameters['sn'];
        if (empty($sn_s)) {
            throw new AlibabaproductException(BookingException::BOOKING_NOT_EXISTS, BookingException::BOOKING_NOT_EXISTS_NO);
        }

        $sn_arr = explode(',', $sn_s);
        $count  = count($sn_arr);

        // 获取支付信息并校验拼团用户是否付款
        //$parameters['trade_order_sn'] = 0;
        $parameters['stats'] = 1;

        $list = Booking::getBookingList($parameters);
        if (!isset($list)) {
            throw new BookingException(BookingException::BOOKING_IS_NOT_EXISTS, BookingException::BOOKING_IS_NOT_EXISTS_NO);
        }
        if ($count != $list['meta']['total']) {
            throw new BookingException(BookingException::BOOKING_IS_NOT_EXISTS, BookingException::BOOKING_IS_NOT_EXISTS_NO);
        }
        $booking = $list['data'];

        $product_id = $booking[0]['product_id'];
        $num        = $booking[0]['num'];
        $sku_id     = $booking[0]['sku_id'];
        $member_id  = $booking[0]['member_id'];
        $price      = $booking[0]['price'];
        // 调用1688接口，校验商品库存
//        $coupon = new Coupon($product_id, $num, $member_id, $sku_id);
//
//        $ali_store = $coupon->checkStoreFromAlibaba();
//
//        if ($ali_store !== true)
//            throw new AlibabaproductException(ALIBABAPRODUCT_INVALID_STORE, ALIBABAPRODUCT_INVALID_STORE_NO);

        // 判断是否需要机器人参与拼团
        $jqmem = ($count == 1) ? 1 : 0;
        //获胜者
        $k = Order::winMember($count);

        $order_data = Order::orderData($booking, $jqmem, $k);

        // 拼团商品需要在订单表创建订单
        $order = Order::createOrder($order_data);

        // 调用1688下单接口
        // 调用1688协议支付接口
        //真正用户拼团成功，到1688下单
        $alibaba_order = [];
        if ($order_data['member_id']) {
            $aliOrder      = [
                'sku_id'     => $sku_id,
                'address_id' => $order_data['address_id'],
                'product_id' => $product_id,
                'num'        => $num,
                'member_id'  => $order_data['member_id'],
                'sn'         => $order_data['sn'],
                'price'      => $price
            ];
            $alibaba_order = Order::aliCreateOrder($aliOrder);
        }
        $order_data['alibaba_order'] = $alibaba_order;

        $order = Order::handleOrder($order_data);
        return $this->_responseJson($order);
    }

    public function orderAction()
    {

        $parameters              = Registry::get('parameters');
        $parameters['member_id'] = Registry::get('jwt_info')->id;
        //代付款
        if ($parameters['stats'] == 0) {
            $order_list = Booking::getBookingList($parameters);
        } else {
            $order_list = Order::getOrderList($parameters);
        }
        return $this->_responseJson($order_list);
    }

    public function operateAction()
    {
        $parameters = Registry::get('parameters');

        // 判断action的值是否为refund或return
        if (!in_array($parameters['action'], ['refund', 'return'])) {
            // 若不是，则提示用户"非法退款、退货操作"
            throw new OrderException(OrderException::ORDER_OPERATE_FAILURE, OrderException::ORDER_OPERATE_FAILURE_NO);
        }
        //判断订单状态
        $order = Order::getOrderBySn($parameters['order_sn']);
        if (empty($order) || empty($order['trade_order_sn']) || $order['refund_stats'] != 0) {
            throw new OrderException(OrderException::ORDER_IS_NOT_EXISTS, OrderException::ORDER_IS_NOT_EXISTS_NO);
        }

        if ($parameters['action'] == 'refund') {
            // 判断订单状态是否为"待发货"
            if ($order['stats'] != 1) {
                throw new OrderException(OrderException::ORDER_STATS_WAIT, OrderException::ORDER_STATS_WAIT_NO);
            }
            $parameters['type'] = 1;
        } else {
            if ($order['stats'] != 2) {
                throw new OrderException(OrderException::ORDER_STATS_ALREADY, OrderException::ORDER_STATS_ALREADY_NO);
            }
            $parameters['type'] = 2;
        }
        // 将退货/退款原因、退货凭证写入数据库
        $album_arr = [];
        // 存在图片，插入图片后将返回结果的id赋值给parameters_arr的album_id键
        if (!empty($parameters['album'])) {
            $current_time = date('Y-m-d H:i:s', time());
            // 生成插入album的数组
            $album_insert_arr = ['type'       => 3, 'album' => $parameters['album'], 'stats' => 1,
                                 'created_at' => $current_time, 'updated_at' => $current_time];
            // 插入数据库 并将返回结果的id赋值给parameters_arr的album_id键
            $album_res = Album::createAlbum($album_insert_arr);

            $parameters['album_id'] = $album_res['id'];
        }

        $info                   = RefundInfo::createRefundInfo($parameters);
        $parameters['refundId'] = $info['id'];
        $msg                    = Order::refundReturn($parameters, $order);
        return $this->_responseJson(new stdClass(), '000', $msg);
    }

    public function refundAction()
    {
        $parameters = Registry::get('parameters');
        //判断订单状态
        $order = Order::getOrderBySn($parameters['order_sn']);
        if (empty($order) || empty($order['trade_order_sn']) || $order['refund_stats'] != 2) {
            throw new OrderException(OrderException::ORDER_IS_NOT_EXISTS, OrderException::ORDER_IS_NOT_EXISTS_NO);
        }
        // 物流公司编码
        $logistics_company_no = $parameters['logistics_company_no'];
        // 运单号
        $freight_bill = $parameters['freight_bill'];
        // 发货说明，内容在2-200个字之间
        $description = $parameters['description'];
        // 凭证图片URLs，uploadRefundVoucher接口返回结果
        //$vouchers = ['http://www.ylmall.com/upload/product_main_image/5e817f251cdb7.jpg', 'http://www.ylmall.com/upload/product_main_image/5e8208f86ca55.png'];
        // 存在图片，插入图片后将返回结果的id赋值给parameters_arr的album_id键
        if (!empty($parameters['album'])) {
            $current_time = date('Y-m-d H:i:s', time());
            // 生成插入album的数组
            $album_insert_arr = ['type'       => 3, 'album' => $parameters['album'], 'stats' => 1,
                                 'created_at' => $current_time, 'updated_at' => $current_time];
            // 插入数据库 并将返回结果的id赋值给parameters_arr的album_id键
            $album_res = Album::createAlbum($album_insert_arr);

            $parameters['album_id'] = $album_res['id'];
            $vouchers               = explode(',', $parameters['album']);
            // 上传凭证
            //$vouchers_arr = Alibaba::tradeUploadRefundVoucher($order['sn'], $vouchers);
            unset($parameters['album']);
        }


        $res = Alibaba::tradeRefundReturnGoods($order['trade_order_sn'], $logistics_company_no, $freight_bill, $description, $vouchers_arr);
        if ($res['success'] == true) {
            //记录物流信息
            $logistics = serialize($parameters);
            $info      = RefundInfo::getRefundInfoBySn($order['sn']);
            $infodata  = ['id' => $info['id'], 'logistics' => $logistics];
            RefundInfo::editInfo($infodata);
            return $this->_responseJson(new stdClass(), '000', '提交成功');
        } else {
            Registry::get('order_log')->err("退货订单的快递信息,sn编号:" . $order['sn'] . ", 原因: " . $res['errorInfo']);
            throw new OrderException(OrderException::ORDER_STATS_ALREADY, OrderException::ORDER_STATS_ALREADY_NO);

        }
    }
}
